package com.ymtc.ibm.code;
/**
 */

import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;

public class MQClientGet {

	private String hostname = "127.0.0.1";
	private int port = 1414; 
	private String channel = "CHL.SVRCONN"; 
	private String qManager = "QM_TEST"; 
	private MQQueueManager qMgr; 
	private static String qName = "IN.Q";
	private MQQueue queue;

	public static void main(String[] args) {		
		MQClientGet mqc = new MQClientGet();
		mqc.runPutMsg();
	}


	public void MQStart() {
		try {
			MQEnvironment.hostname = hostname; 
			MQEnvironment.channel = channel; 
			MQEnvironment.port = port;
			MQEnvironment.CCSID = 1208;
		
			qMgr = new MQQueueManager(qManager);
			int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT ;
			queue = qMgr.accessQueue(qName, openOptions);
			System.out.println(">>> Open Queue successful!");
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void MQStop() {
		try {
			queue.close();
			qMgr.disconnect();
		} catch (MQException ex) {
			System.out.println("stop err!!!!");
		}
	}

	public void sendMsgToQueue() {
		try {
			MQGetMessageOptions gmo = new MQGetMessageOptions();
			gmo.options = gmo.options + MQConstants.MQGMO_SYNCPOINT;
			gmo.options = gmo.options + MQConstants.MQGMO_WAIT;
			gmo.waitInterval = 100000;
			gmo.matchOptions = MQConstants.MQMO_NONE;

			//gmo.matchOptions = MQConstants.MQMO_MATCH_MSG_ID;
			
			//Thread.sleep(10000);
			
			System.out.println(">>> Start to get messages!");
			MQMessage msg = new MQMessage();
			queue.get(msg, gmo);
			System.out.println(">>> Message Length is : " + msg.getDataLength());
			System.out.println(">>> Message PutDate is : " + msg.putDateTime.getTime());
			byte[] buffer = new byte[msg.getDataLength()];
			msg.readFully(buffer);
			System.out.println(">>> Message is : " + new String(buffer,"GBK"));
			qMgr.commit();
			//qMgr.backout();
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void runPutMsg() {
		try {
			MQStart();
			sendMsgToQueue();
			MQStop();
		} catch (Exception e) {
			e.printStackTrace(System.out);
			MQStop();
			System.exit(2);
		}
	}
}